package com.yanfan.zutai.service.impl;

import cn.hutool.core.date.DateUtil;
import com.yanfan.common.core.domain.entity.SysUser;
import com.yanfan.common.core.redis.RedisCache;
import com.yanfan.common.utils.sign.Md5Utils;
import com.yanfan.iot.model.login.LoginIdValue;
import com.yanfan.zutai.mapper.BCommonMapper;
import com.yanfan.zutai.service.BCommonService;
import com.yanfan.zutai.util.Detect;
import me.zhyd.oauth.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import static com.yanfan.common.utils.SecurityUtils.getLoginUser;

@Service
public class BCommonServiceImpl implements BCommonService {

    @Autowired
    private BCommonMapper bCommonMapper;
    @Autowired
    private RedisCache redisCache;

    @Override
    public Double getdictValue(String dictType) {
        if (Detect.notEmpty(dictType)) {
            return bCommonMapper.getdictValue(dictType);
        } else {
            return 0.0;
        }
    }

    @Override
    public String getWorkNumber(String workType, String dept) {
        StringBuffer stringBuffer = new StringBuffer();
        if ("工单管理".equals(workType)) {
            stringBuffer.append("1_");
        } else if ("例行巡检".equals(workType)) {
            stringBuffer.append("2_");
        } else {
            stringBuffer.append("3_");
        }
        stringBuffer.append(dept + "_");
        stringBuffer.append(DateUtil.format(new Date(), "yyyyMMdd") + "_");
        Integer workNumber = bCommonMapper.getWorkNumber(workType, dept);
        int num = 1;
        if (workNumber != null) {
            num = num + workNumber;
        }
        String numStr = num + "";
        if (numStr.length() == 1) {
            numStr = "0000" + numStr;
        } else if (numStr.length() == 2) {
            numStr = "000" + numStr;
        } else if (numStr.length() == 3) {
            numStr = "00" + numStr;
        } else if (numStr.length() == 4) {
            numStr = "0" + numStr;
        }
        stringBuffer.append(numStr);
        return stringBuffer.toString();
    }

    @Override
    public String getCurrUserLoginId() {
        final String LOGIN_SOCIAL_REDIS_KEY = "login:social:user:";
        final Integer LOGIN_SOCIAL_EXPIRE_TIME = 60;

        SysUser sysUser = getLoginUser().getUser();

        String loginId = Md5Utils.hash(sysUser.getUserId() + RandomUtil.randomString(32));
        String key = LOGIN_SOCIAL_REDIS_KEY + loginId;
        LoginIdValue loginIdValue = new LoginIdValue();
        loginIdValue.setPassword(sysUser.getPassword());
        loginIdValue.setUsername(sysUser.getUserName());
        loginIdValue.setDeptId(sysUser.getDeptId());
        redisCache.setCacheObject(key, loginIdValue, LOGIN_SOCIAL_EXPIRE_TIME, TimeUnit.SECONDS);
        return loginId;
    }
}
